package datenhaltung;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class DB_Basis {

	Connection connection;
	String table;
	
	DB_Basis(String table){		
		this.setTable(table);		
	}
		
	public void insert(String values) throws ClassNotFoundException, SQLException{

		values = values.replace( "false" , "0" );
		values = values.replace( "true" , "1" );
		this.dbAcess().executeUpdate("INSERT INTO car VALUES("+ values +")");
	}
			
	public ResultSet select(String condition) throws SQLException, ClassNotFoundException{
		
		ResultSet rs = this.dbAcess().executeQuery("SELECT * FROM "+this.getTable()+" WHERE "+condition);
		
		return rs;
	}
	
	public void update(String changes, String condition) throws SQLException, ClassNotFoundException{
		
		String sql_string = "UPDATE "+this.getTable()+" SET "+changes+" WHERE "+condition+";";
		
		this.dbAcess().executeUpdate(sql_string);		
	}
	
	public void delete(String condition) throws ClassNotFoundException, SQLException {
		
		this.dbAcess().executeUpdate("DELETE FROM "+this.getTable()+" WHERE "+condition);
	}
	
	public int countByCondition(String condition) throws ClassNotFoundException, SQLException{
		
		int j = 0;
		String sql_string = "SELECT * FROM "+this.getTable()+" WHERE "+condition;
				
		ResultSet rs = this.dbAcess().executeQuery(sql_string);
			
    	while(rs.next())
    	{
    		j++;
    	}
		rs.close();
		
		this.dbClose();		
		return j;		
	}
	
	private Statement dbAcess() throws SQLException, ClassNotFoundException{
		
		Class.forName("org.sqlite.JDBC");
		this.setConnection(DriverManager.getConnection("jdbc:sqlite:Autohaus.db"));
	
		Statement statement = this.getConnection().createStatement();
		
		return statement;
	}
	
	public void dbClose() throws SQLException{		
		this.getConnection().close();		
	}
	
	private void setTable(String table){ this.table = table;}
	private String getTable(){return this.table;}	
	private void setConnection(Connection connection){ this.connection = connection;}
	private Connection getConnection(){return this.connection;}
	
}



